package com.ques.service.impl;

import com.ques.dao.UserDao;
import com.ques.entity.MailMessage;
import com.ques.pojo.User;
import com.ques.service.UserService;
import com.ques.utils.MailUtil;
import com.ques.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * @author zq  2020-01-05
 */
@Service
public class UserServiceImpl implements UserService {
    private static final String codeStr = "0123456789zxcvbnmlkjhgfdsaqwertyuiopZXCBVNMLKJHGFDSAPOIUYTREWQ";
    private static final int codeStrLen = 62;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private UserDao userDao;

    @Autowired
    MailUtil mailUtil;

    @Autowired
    MailMessage mailMessage;

    @Override
    public User login(User user) {
        return userDao.selectUserByUsernameAndPassword(user);
    }

    @Override
    public void addUserToken(String token, String id) {
        Jedis jedis = redisUtil.getJedis();
        jedis.set("user:" + id + ":token", token);
        jedis.close();
    }

    @Override
    public String sendCode(String userEmail) {
        String code = createCode();
        try {
            MailMessage to = mailMessage.content("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' />" +
                    "</head><body>" +

                    "<div id='qm_con_body'><div id='mailContentContainer' class='qmbox qm_con_body_content qqmail_webmail_only' style=''><h2>问卷后台，验证码：<span style='color: red;'>" + code + "</span></h2><div style='line-height: 22px;'>感谢支持 ,验证码5分钟内有效 <br> 如发错误，请忽略！！！</div>"
                    +
                    "</body></html>").to(userEmail);
            mailUtil.sendMail(to);
//            进行缓存
            Jedis jedis = redisUtil.getJedis();
            jedis.setex("user:" + userEmail + ":code", 5 * 60, code);
            jedis.close();
        } catch (AddressException e) {
            e.printStackTrace();
            return "邮箱地址错误";
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("信息有误");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "邮箱不支持";
        } catch (Exception e) {
            return "维护中";
        }
        return null;
    }

    private String createCode() {
        Random random = new Random();

        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int nextInt = random.nextInt(codeStrLen);
            stringBuilder.append(codeStr.charAt(nextInt));
        }
        return stringBuilder.toString();
    }

    @Override
    public String equalCode(String username, String code) {
        Jedis jedis = redisUtil.getJedis();
        String codeDb = jedis.get("user:" + username + ":code");

        if (StringUtils.isEmpty(codeDb )){
            return "验证码已过期,请重新获取验证码"  ;
        }
        boolean isEqual = StringUtils.pathEquals(code, codeDb);

        if (isEqual){
// 自动过期
            return  null ;
        }else{
            return "验证码错误" ;
        }
    }

    @Override
    public User getUserInfo(String userId) {
        User user =  userDao.selectUserInfoById(userId);
        return user;
    }

    @Override
    public boolean loginOut(String userId) {
        Jedis jedis = redisUtil.getJedis();
        jedis.del("user:" + userId + ":token");
        return true;
    }
}
